<template>
  <el-dialog
    top="30px"
    width="90%"
    title="解保查看"
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="beforeClose"
  >
    <div>
      <h5 class="section-title">解保表信息</h5>
      <table class="table table-bordered vertical-align-middle text-center table-sm table-confirm">
        <colgroup>
          <col width="15%" />
          <col width="18%" />
          <col width="15%" />
          <col width="18%" />
          <col width="15%" />
          <col width="19%" />
        </colgroup>
        <tr>
          <td>解保批号</td>
          <td>{{ batchData.batch_no }}</td>
          <td>提供机构</td>
          <td>{{ batchData.submit_client_name }}</td>
          <td>接收日期</td>
          <td>{{ batchData.createTime }}</td>
        </tr>
        <tr>
          <td>解保总额</td>
          <td>{{ batchData.project_funds }} 万元</td>
          <td>解保数量</td>
          <td>{{ batchData.project_count }}</td>
          <td>回复状态</td>
          <td>{{ enumUnguaConfirmStatus[batchData.project_status] || '-' }}</td>
        </tr>
      </table>

      <h5 class="section-title">解保明细表</h5>
      <table class="table table-bordered vertical-align-middle text-center table-sm">
        <colgroup>
          <col width="5%" />
          <col width="13%" />
          <col width="14%" />
          <col width="14%" />
          <col width="14%" />
          <col width="13%" />
          <col width="14%" />
          <col width="13%" />
        </colgroup>
        <tr>
          <td class="td-label">序号</td>
          <td class="td-label">借款客户</td>
          <td class="td-label">客户类型</td>
          <td class="td-label">贷款金额</td>
          <td class="td-label">放款日期</td>
          <td class="td-label">到期日期</td>
          <td class="td-label">项目状态</td>
          <td class="td-label">操作</td>
        </tr>
        <tr v-for="(p, index) of tableData" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ p.customer_name }}</td>
          <td>{{ p.org_class_name }}</td>
          <td>{{ p.warranty_amount }}</td>
          <td>{{ p.loadDate }}</td>
          <td>{{ p.loadEndDate }}</td>
          <td>{{ p.loadBehStatus }}</td>
          <td>
            <el-button type="text" @click="handleView(p)">查看</el-button>
          </td>
        </tr>
        <tr v-if="!tableData.length">
          <td colspan="8" class="text-muted text-center">暂无数据</td>
        </tr>
      </table>

      <h5 class="section-title">附件资料</h5>
      <div class="border px-2 pt-2">
        <attach-list :attath-data="batchAttachData"></attach-list>

        <div class="section-divider"></div>

        <attach-list :attath-data="confirmAttachData">
          <template v-if="editable" slot="tagAction" slot-scope="{ tagData }">
            <input
              type="file"
              ref="uploadInput"
              class="d-none"
              multiple
              :accept="mineTypes"
              @change="handleFileChange"
            />
            <el-button
              type="primary"
              size="small"
              class="btn-long mb-1"
              icon="el-icon-upload2"
              @click="handleUpload(tagData.tag)"
            >
              上传
            </el-button>
          </template>

          <template v-if="editable" slot="attachAction" slot-scope="{ attachData, index }">
            <el-button type="text" @click="handleDeleteFile(attachData, index)">删除</el-button>
          </template>
        </attach-list>
      </div>

      <div class="text-center mt-5" v-if="editable">
        <el-button type="primary" class="btn-long" :loading="saveLoading" @click="handleConfirm">
          回复
        </el-button>
        <el-button class="btn-long" :disabled="saveLoading" @click="beforeClose">取消</el-button>
      </div>
    </div>

    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="viewAttachNo"
      :tab-name="viewTabName"
      :query-id="viewQueryId"
    ></project-view-dialog>
  </el-dialog>
</template>

<script>
import { enumUnguaConfirmStatus } from '@/bank/views/limit/postloan/mixins'
import { enumLoanbehStatus } from '@/bank/views/limit/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { attachAdapter, fileAdapter } from '@/bank/components/attach/index'
import { uploadOss, deleteOss } from '@/common/api/oss'

import ProjectViewDialog from '@/bank/views/business/limit/history/ProjectViewDialog'
import AttachList from '@/bank/components/attach/List'

export default {
  components: {
    ProjectViewDialog,
    AttachList,
  },
  props: {
    visible: Boolean,
    batchData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
  },
  data() {
    return {
      enumUnguaConfirmStatus,

      params: {},
      batchKey: 'un_gua_batch_id',
      tableName: 'datum_one_county_industry',
      attachTableName: 'datum_customer_attachment',
      order: {},
      tableData: [],

      batchAttachList: [],
      batchAttachTag: '解保明细附件',

      confirmAreadyList: [],
      confirmDeleteList: [],

      confirmAttachList: [],
      confirmAttachTag: '解保确认附件',
      mineTypes: '*',

      // 查看
      viewVisible: false,
      viewQueryId: '',
      viewAttachNo: '',
      viewTabName: 'detail',

      saveLoading: false,
    }
  },
  computed: {
    editable() {
      return !this.viewMode && +(this.batchData.project_status || 0) < 2
    },
    batchNo() {
      return this.batchData[this.batchKey]
    },
    batchAttachData() {
      return [
        {
          tag: this.batchAttachTag,
          attachs: this.batchAttachList,
        },
      ]
    },
    confirmAttachData() {
      return [
        {
          tag: this.confirmAttachTag,
          attachs: [...this.confirmAreadyList, ...this.confirmAttachList],
        },
      ]
    },
  },
  watch: {
    visible: {
      handler: function (val) {
        if (val) {
          this.getBatchAttach()
          this.getConfirmAttach()
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.reset()
      this.$emit('update:visible', false)
    },

    reset() {
      this.confirmAttachList.forEach(file => {
        if (file.file) revokeObjectURL(file.url)
      })
      this.confirmAttachList = []
      this.confirmAreadyList = []
      this.confirmDeleteList = []
      this.batchAttachList = []

      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },

    getData() {
      if (!this.batchNo) return

      this.params[`${this.batchKey}.eq`] = this.batchNo
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? []
          this.tableData = data.map(this.dataAdapter)
        })
        .finally(() => {
          this.loading = false
        })
    },

    dataAdapter(item) {
      item.submitDate = this.subDate(item.res_time)
      item.loadDate = this.subDate(item.load_date)
      item.loadEndDate = this.subDate(item.load_end_date)
      item.loadBehStatus = enumLoanbehStatus[item.load_beh_status]
      return item
    },

    subDate(date = '') {
      return date.substring(0, 10)
    },

    getConfirmAttach() {
      if (!this.batchNo) {
        return
      }

      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.attachTableName,
          { 'customer_related_id.eq': this.batchNo },
          { create_time: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.confirmAreadyList = data.map(attachAdapter)
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleView(row = {}) {
      this.viewQueryId = row.customer_related_id
      this.viewAttachNo = row[this.batchKey]
      this.viewTabName = 'detail'
      this.viewVisible = true
    },

    getBatchAttach() {
      this.batchAttachList = []
    },

    handleUpload() {
      if (!this.batchNo) {
        return this.$message.error('没有项目附件的相关信息，不能上传附件')
      }

      const { uploadInput } = this.$refs
      uploadInput.click()
    },

    handleDeleteFile(attach, index) {
      const areadyCount = this.confirmAreadyList.length
      if (index < areadyCount) {
        this.confirmAreadyList.splice(index, 1)
        this.confirmDeleteList.push(attach)
      } else {
        revokeObjectURL(attach.attachment)
        this.confirmAttachList.splice(index + areadyCount, 1)
      }
    },

    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        const item = fileAdapter(files[i])
        item.attachment = item.url
        this.confirmAttachList.push(item)
      }
      this.handleClear()
    },
    handleClear() {
      const { uploadInput } = this.$refs
      uploadInput.value = ''
    },

    handleConfirm() {
      if (this.confirmAttachList.length === 0) {
        return this.$message.error('请先选择文件')
      }

      this.$utils
        .msgbox({
          message: '确定回复？',
          type: 'warning',
          beforeClose: () => {
            this.saveLoading = true
            return this.confirmData()
          },
        })
        .then(res => {
          this.$message.success('回复成功！')
          this.beforeClose()
          this.$emit('success', res)
        })
        .catch(err => {
          this.$message.error('回复失败，请重试！')
          throw new Error(err)
        })
        .finally(() => {
          this.saveLoading = false
        })
    },

    async confirmData() {
      const res = await this.handleUploadFile()
      await this.updateConfirmStatus(res)
      this.deleteAttachAfterConfirm()
    },

    // 上传OSS
    async handleUploadFile() {
      const { confirmAttachList } = this

      const promises = confirmAttachList.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/attach/${this.batchNo}`,
          type: 1,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )

      this.loading = true
      return Promise.all(promises)
        .then(list => {
          const attachData = list.map((url, index) => {
            const { viewType, name } = confirmAttachList[index]
            return {
              attachment: url,
              attachment_type: this.confirmAttachTag,
              customer_related_id: this.batchNo,
              file_type: viewType === 'image' ? 1 : 2,
              remark: name,
            }
          })
          return this.addData(attachData).then(res => ({ res, list }))
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 添加附件表
    async addData(data) {
      return this.$api.addBatch('credit', this.attachTableName, data)
    },

    updateConfirmStatus(res) {
      return this.$api
        .updateData(this.$serviceName, 'un_gua_batch', this.batchNo, {
          project_status: 2,
        })
        .catch(err => {
          const { list = [] } = res || {}
          this.deleteAttachByBatchNo(list)
          throw new Error(err)
        })
    },

    deleteAttachByBatchNo(list) {
      return this.$api
        .deleteDataBody(this.$serviceName, this.attachTableName, {
          customer_related_id: this.batchNo,
        })
        .then(() => {
          deleteOss(list)
        })
    },

    deleteAttachAfterConfirm() {
      const { confirmDeleteList } = this
      if (!confirmDeleteList.length) return

      return Promise.all(
        confirmDeleteList.reduce((prev, curr) => {
          prev.push(this.deleteAttachRecord(curr))
          return prev
        }, [])
      )
    },

    deleteAttachRecord(attach) {
      return this.$api.deleteData(this.$serviceName, this.attachTableName, attach.id).then(res => {
        deleteOss(attach.attachment)
        return res
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.section-title {
  font-size: 1.1rem;
  font-weight: bold;
}

.section-divider {
  height: 1px;
  border-bottom: 1px dotted $gray-200;
  margin-bottom: 0.5rem;
}

.table-confirm tr > td:nth-child(2n + 1) {
  background-color: $gray-100;
}
</style>
